package com.deepocean.utils;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

@Component
public class LanguageUtil {
    private static final String LANGUAGE = "language";

    public Locale getLocale() {
        return new Locale(getLanguage());
    }

    public HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    public String getLanguage() {
        Cookie[] cookies = getRequest().getCookies();
        String language = "zh";
        for (Cookie cookie : cookies) {
            if (LANGUAGE.equals(cookie.getName())) {
                language = cookie.getValue();
            }
        }
        return language;
    }
}
